/*
 * @Author: your name
 * @Date: 2021-06-26 10:27:15
 * @LastEditTime: 2021-06-26 10:51:01
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \6.26作业\yyds\conroller\user.js
 */
const query = require("../db/mysql")
const { success, error } = require("../model/model")
const {md5}=require("utility")
const jwt=require("jsonwebtoken")

class userP {
    zhuce = async (ctx) => {
        const { username, passord, nickname } = ctx.request.body;
        const sql = `select * from users where username="${username}"`
        const sqla = await query(sql)
        if (sqla.length) {
            ctx.body = success("账号存在")
            return
        }
        const isHave=`insert into users(username,passord,nickname) value("${username}","${passord}","${nickname}") `
        const data=await query(isHave)
        if(data.affectedRows===1){
            ctx.body=success("注册成功")
        }else{
            ctx.body=error("注册失败")
        }
    }
    login=async(ctx)=>{
        const {username,passord}=ctx.request.body
        const sql=`select * from users where username="${username}" and passord="${(md5(String(passord)))}"`
        const data=await query(sql)
        if(data.length){
            ctx.body=success({
                data:data[0],
                token:jwt.sign({id:data[0].id},"1812A")
            },"登陆成功")
        }else{
            ctx.body=error("登录失败")
        }
    }
}

module.exports=new userP()